package com.forlove.app.manager.async;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.content.AsyncTaskLoader;
import android.text.TextUtils;

import com.forlove.app.R;
import com.forlove.app.common.utils.CipherUtils;
import com.forlove.app.common.utils.CryptAES;
import com.forlove.app.common.utils.StringUtils;
import com.forlove.app.manager.QRCodeManager;
import com.forlove.app.manager.ServerManager;
import com.forlove.app.manager.UserManager;
import com.forlove.app.qselect.login.entity.UserEntity;

import java.io.IOException;
import java.net.URL;

/**
 * Created by yjl on 2017/10/23.
 */

public class QRCodeAsync extends AsyncTaskLoader<Bitmap> {
    private String content;
    public static int ASYNC_ID = 20003;

    public QRCodeAsync(Context context) {
        super(context);
    }

    @Override
    public Bitmap loadInBackground() {
        try {
            UserEntity userEntity = UserManager.getUesrInfo(getContext());
            if (userEntity != null && !TextUtils.isEmpty(userEntity.userMobile)) {
                String mobile = userEntity.userMobile;
                String aesKey = CipherUtils.md5(QRCodeManager.scan_key);
                content = CryptAES.AES_Encrypt(aesKey, mobile);
            }
            Bitmap bitmap;
            if (StringUtils.isNotEmpty(userEntity.mUserImage)) {
                bitmap = BitmapFactory.decodeStream(
                        new URL(ServerManager.getImageUrl() + userEntity.mUserImage).openStream());
            } else {
                bitmap = BitmapFactory.decodeResource(getContext().getResources(), R.mipmap.image_mine_friend_avatar);
            }
            boolean isSuccess = QRCodeManager.createQRImage(content, 800, 800, bitmap);
            if (isSuccess) {
                Bitmap qrcodeMap = BitmapFactory.decodeFile(QRCodeManager.codeUser);
                return qrcodeMap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    @Override
    protected void onStartLoading() {
        super.onStartLoading();
        forceLoad();
    }
}
